Page({
  /**
   * 页面的初始数据
   */
  data: {
    needLogin: false, // 是否需要登陆
    checked: false, // 是否勾选条款
    randomNum: 1,
    showLoading: false,
    showPrivacy: false
  },

  /* 获取随机整数 */
  getrandomNum(m, n) {
    var num = Math.floor(Math.random() * (m - n) + n);
    return num;
  },
  toShouyeClick() {
    clearInterval(this.data.setItv);
    this.setData({
      setItv: null,
    });
    this.data.setItv = null;
    wx.switchTab({
      url: "/pages/shouye/shouye",
    });
  },
  onChange(e) {
    this.setData({
      checked: e.detail,
    });
  },
  loginByPhone() {
    if (!this.data.checked) {
      wx.showToast({
        title: "请阅读并同意协议",
        icon: "none",
      });
      return;
    }
  },
  goBindTel(code) {
    const params = {
      code: code
    }
    getApp().globalData.request(
      "/user/bindOpenId",
      params,
      "POST"
    ).then(res => {
      console.log(res, 'openId');
    });
  },
  async backPhone(e) {
    console.log('111')
    if (e.detail.code) {
      this.setData({
        showLoading: true,
      });
      const code = e.detail.code || "";
      console.log(code, "code");
      const params = {
        code: code,
        needToken: true,
      };

      // 登陆
      const {
        data
      } = await getApp().globalData.request(
        "/login/oneClickLogin",
        params,
        "POST"
      );
      console.log(data, "data");
      if (data) {
        // 绑定手机号
        const _this = this;
        // wx.login({
        //   success: (res) => {
        //     _this.goBindTel(res.code)
        //   },
        // })
        // wx.setStorageSync("token", '963696da-5a1c-415a-97d9-f1f8182237e2');
        // wx.setStorageSync("token", 'c588f048-7e0e-42c9-a966-077e7a3bbe79');
        wx.setStorageSync("token", data.access_token);
        const res = await getApp().globalData.request(
          "/login/getCurrentUserInfo", {
            needToken: true
          },
          "POST"
        );
        console.log(res.data, 'res.datares.data')
        wx.setStorageSync("userInfo", res.data);
        if (data.access_token) {
          // 延迟1秒关闭loading
          setTimeout(() => {
            wx.switchTab({
              url: "/pages/shouye/shouye",
              success: function (e) {
                var page = getCurrentPages().pop();
                if (page == undefined || page == null) return;
                page.onLoad();
              },
            });
          }, 1000);
        }
      } else {
        // 延迟1秒关闭loading
        setTimeout(() => {
          this.setData({
            showLoading: false,
          });
          wx.showToast({
            title: '登录失败',
            icon: 'error'
          })
        }, 1000);
      }
    }
  },
  intoSy() {
    wx.setStorageSync("token", "");
    wx.switchTab({
      url: "/pages/shouye/shouye",
      success: function (e) {
        var page = getCurrentPages().pop();
        if (page == undefined || page == null) return;
        page.onLoad();
      },
    });
  },
  openAgreement() {
    wx.navigateTo({
      url: "/pages/userAgreement/userAgreement",
    });
  },
  async initTo() {
    // 判断缓存中是否有手机号（暂时的）
    const userInfo = wx.getStorageSync('userInfo') || ''
    let token = wx.getStorageSync("token");
    this.setData({
      needLogin: token === 'cxgc123456' ? true : false,
    });
    if (!this.data.needLogin) {
      // 登录
      const phone = userInfo ? userInfo.phone || '' : ''
      if (phone) {
        const params = {
          phone: phone,
          // phone: '15950059911'  // 王博
          // phone: '15921390309' //管理员
          // phone: '13814994095' //传呼专员 营销状态
          // phone: '17712266670' //客户经理 营销状态
          
        }
        console.log(params, 'params');
        const res = await getApp().globalData.request(
          "/login/oneClickLoginUsePhone",
          params,
          "POST"
        );
        if(res.data) {
          console.log(res, '手机号登录返回');
          // 更新缓存中的token
          wx.setStorageSync('token', res.data.access_token)
        }
        setTimeout(() => {
          wx.switchTab({
            url: "/pages/shouye/shouye",
          });
        }, 1400);
      } else {
        setTimeout(() => {
          wx.switchTab({
            url: "/pages/shouye/shouye",
          });
        }, 1400);
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    /* 获取1-3之间的随机整数 */
    var num = this.getrandomNum(1, 4);
    this.setData({
      randomNum: num,
    });
    // wx.onNeedPrivacyAuthorization((resolve, eventInfo) => {
    // // wx.requirePrivacyAuthorize ((resolve, eventInfo) => {
    //   console.log('触发本次事件的接口是：' + eventInfo.referrer)
    //   // 需要用户同意隐私授权时
    //   // 弹出开发者自定义的隐私授权弹窗
    //   this.setData({
    //     showPrivacy: true
    //   })
    //   this.resolvePrivacyAuthorization = resolve
    //   console.log(this.resolvePrivacyAuthorization, 'this.resolvePrivacyAuthorization')
    // })

    // wx.getUserProfile({
    //   success: console.log,
    //   fail: console.error
    // })
  },

  handleAgreePrivacyAuthorization() {
    // 用户点击同意按钮后
    this.resolvePrivacyAuthorization({
      buttonId: 'agree-btn',
      event: 'agree'
    })
    // 用户点击同意后，开发者调用 resolve({ buttonId: 'agree-btn', event: 'agree' })  告知平台用户已经同意，参数传同意按钮的id。为确保用户有同意的操作，基础库在 resolve 被调用后，会去检查对应的同意按钮有没有被点击过。检查通过后，相关隐私接口会继续调用
    // 用户点击拒绝后，开发者调用 resolve({ event:'disagree' }) 告知平台用户已经拒绝
  },

  closeModal() {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initTo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});